import os
import shutil
from string import Template
from ebooklib import epub
import chardet

def read_txt_file(file_path):
    """读取txt文件内容，使用chardet检测编码"""
    with open(file_path, 'rb') as f:
        raw_data = f.read()
        
    # 使用chardet检测文件编码
    result = chardet.detect(raw_data)
    encoding = result['encoding'] or 'utf-8'  # 如果检测失败，默认使用utf-8
    
    try:
        content = raw_data.decode(encoding)
        return content
    except UnicodeDecodeError:
        # 如果检测的编码解码失败，尝试utf-8和gbk
        encodings_to_try = ['utf-8', 'gbk']
        for enc in encodings_to_try:
            if enc != encoding:
                try:
                    content = raw_data.decode(enc)
                    return content
                except UnicodeDecodeError:
                    continue
        # 所有尝试都失败，使用replace策略
        return raw_data.decode('utf-8', errors='replace')

def parse_chapters(content):
    """解析txt文件中的章节"""
    # 使用------------分割章节
    raw_chapters = content.split('------------')
    chapters = []
    
    for chapter_content in raw_chapters:
        chapter_content = chapter_content.strip()
        if not chapter_content:
            continue
            
        # 提取标题（第一行）
        lines = chapter_content.split('\n')
        title = lines[0].strip()
            
        # 提取正文
        body = '\n'.join(lines[1:]).strip()
        
        # 去除空行和前后空格
        body = '\n'.join([line.strip() for line in body.split('\n') if line.strip()])
        
        # 去除没有正文内容的章节
        if body:
            chapters.append({
                'title': title,
                'body': body
            })
    
    return chapters

def generate_html(chapters, output_dir):
    """生成HTML文件：目录页为index.html，章节页为chapters/{章节序号}.html"""
    # 创建chapters目录
    chapters_dir = os.path.join(output_dir, "chapters")
    os.makedirs(chapters_dir, exist_ok=True)
    
    # 生成目录页index.html
    substitute_dict = {}
    index_html = None
    with open("index.html", "r", encoding="utf-8") as f:
        index_html = f.read()
    substitute_dict['chapter_list'] = ""
    # 为每个章节生成单独的HTML文件和目录链接
    for i, chapter in enumerate(chapters, 1): 
        # 生成章节链接到目录页
        substitute_dict['chapter_list'] += f"            <li><a href='chapters/{i}.html'><span class='chapter-number'>{i}.</span>{chapter['title']}</a></li>\n"
        
        # 生成章节HTML文件
        chapter_file = os.path.join(chapters_dir, f"{i}.html")
        chapter_html = None
        with open("chapter.html", "r", encoding="utf-8") as f:
            chapter_html = f.read()
        # 章节标题
        substitute_dict['chapter_title'] = chapter["title"]
        
        # 导航链接 - 添加CSS类以便于JS选择
        substitute_dict['last_chapter_href'] = f'<span style="color: #999;">上一章</span>'
        if i > 1:
            substitute_dict['last_chapter_href'] = f'<a href="{i-1}.html" class="prev-chapter">上一章</a>\n'
        substitute_dict['next_chapter_href'] = f'<span style="color: #999;">下一章</span>'
        if i < len(chapters):
            substitute_dict['next_chapter_href'] = f'<a href="{i+1}.html" class="next-chapter">下一章</a>\n'
        
        # 添加章节正文
        substitute_dict['chapter_body'] = ""
        paragraphs = chapter['body'].split('\n')
        for para in paragraphs:
            if para.strip():
                substitute_dict['chapter_body'] += f"            <p>{para}</p>\n"
        
        # 替换模板变量
        chapter_html = Template(chapter_html).substitute(substitute_dict)

        # 保存章节HTML文件
        with open(chapter_file, 'w', encoding='utf-8') as f:
            f.write(chapter_html)
    
    # 完成目录页内容
    index_html = Template(index_html).substitute(substitute_dict)
    # 保存目录页index.html
    index_path = os.path.join(output_dir, "index.html")
    with open(index_path, 'w', encoding='utf-8') as f:
        f.write(index_html)
    # 复制章节页的CSS和JS文件到输出目录
    shutil.copy("chapter.css", chapters_dir)
    shutil.copy("chapter.js", chapters_dir)
    
    return index_path

def generate_epub(chapters, output_dir, novel_title="小说", novel_author="Unknown"):
    """生成epub电子书"""
    # 创建epub书籍对象
    book = epub.EpubBook()
    
    # 设置书籍元数据
    book.set_identifier('novel-001')
    book.set_title(novel_title)
    book.set_language('zh-CN')
    book.add_author(novel_author)
    
    # 创建目录
    book.toc = []
    spine = ['nav']
    
    # 添加封面
    cover_page = epub.EpubHtml(title='封面', file_name='cover.xhtml', lang='zh-CN')
    cover_page.content = f"""
        <div style="text-align: center; margin-top: 100px;">
            <h1>{novel_title}</h1>
            <p>作者: {novel_author}</p>
        </div>
    """
    book.add_item(cover_page)
    spine.append(cover_page)
    
    # 添加各章节
    for i, chapter in enumerate(chapters, 1):
        # 创建章节文件
        chapter_file = f'chapter_{i}.xhtml'
        c = epub.EpubHtml(title=chapter['title'], file_name=chapter_file, lang='zh-CN')
        
        # 构建章节内容
        content = f'<h2>{chapter["title"]}</h2>'
        paragraphs = chapter['body'].split('\n')
        for para in paragraphs:
            if para.strip():
                content += f'<p>{para}</p>'
        
        c.content = content
        
        # 添加章节到书籍
        book.add_item(c)
        book.toc.append(epub.Link(chapter_file, chapter['title'], f'chap_{i}'))
        spine.append(c)
    
    # 添加导航文件
    book.add_item(epub.EpubNcx())
    book.add_item(epub.EpubNav())
    
    # 设置书脊顺序
    book.spine = spine
    
    # 保存epub文件
    epub_path = os.path.join(output_dir, f"{novel_title}.epub")
    epub.write_epub(epub_path, book, {})
    
    return epub_path

def main():
    novel_title = "柯南里的收尸人"
    novel_author = "仙舟"
    # txt文件路径
    txt_path = f"{novel_title}.txt"
    
    print(f"正在读取txt文件: {txt_path}")
    content = read_txt_file(txt_path)
    
    print("正在解析章节...")
    chapters = parse_chapters(content)
    
    # 创建输出目录（按照之前的规则，使用小说名称命名）
    output_dir = os.path.join(os.getcwd(), novel_title)
    os.makedirs(output_dir, exist_ok=True)
    
    print(f"成功解析到{len(chapters)}个章节")
    
    print("正在生成HTML文件...")
    html_path = generate_html(chapters, output_dir)
    print(f"HTML文件已保存至: {html_path}")
    
    print("正在生成EPUB电子书...")
    epub_path = generate_epub(chapters, output_dir, novel_title, novel_author)
    print(f"EPUB文件已保存至: {epub_path}")
    
    print("转换完成！")

if __name__ == "__main__":
    main()